let currentLang = "en"
let dict = {}

async function loadLocale(lang) {
  try {
    const res = await fetch(`/_locales/${lang}/messages.json`)
    if (!res.ok) throw new Error("no locale")
    const messages = await res.json()
    const flat = {}
    for (const key of Object.keys(messages)) {
      flat[key] = messages[key]?.message ?? ""
    }
    return flat
  } catch (_e) {
    return {}
  }
}

export async function applyI18n(lang) {
  currentLang = lang || "en"
  dict = await loadLocale(currentLang)
  translateDOM(document)
}

export function tLocal(key) {
  try {
    const viaChrome =
      typeof chrome !== "undefined" && chrome.i18n && chrome.i18n.getMessage
        ? chrome.i18n.getMessage(key)
        : ""
    if (viaChrome) return viaChrome
  } catch (_e) {
    // ignore and fall back to local dict
  }
  return dict[key] || key
}

export function translateDOM(root) {
  const nodes = root.querySelectorAll("[data-i18n], [data-i18n-title]")
  nodes.forEach((el) => {
    const key = el.getAttribute("data-i18n")
    if (key) {
      el.textContent = tLocal(key)
    }
    const titleKey = el.getAttribute("data-i18n-title")
    if (titleKey) {
      el.setAttribute("title", tLocal(titleKey))
    }
  })
}
